package com.mass.core.activiti.workflow.controller;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.mass.core.utils.AjaxResponse;

import java.io.ByteArrayInputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@RestController
@RequestMapping({"/activiti/model"})
public class ModelController {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    RepositoryService repositoryService;

    public ModelController() {
    }

    @RequestMapping({"/list"})
    public AjaxResponse modelList() {
        List<Model> list = this.repositoryService.createModelQuery().list();
        return AjaxResponse.success("ok", list);
    }

    @SuppressWarnings("deprecation")
	@RequestMapping(
        value = {"/create"},
        method = {RequestMethod.POST}
    )
    public AjaxResponse create(@RequestParam("name") String name, @RequestParam("key") String key, @RequestParam("description") String description, HttpServletRequest request, HttpServletResponse response) {
        try {
            ObjectMapper e = new ObjectMapper();
            ObjectNode editorNode = e.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode stencilSetNode = e.createObjectNode();
            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.put("stencilset", stencilSetNode);
            Model modelData = this.repositoryService.newModel();
            ObjectNode modelObjectNode = e.createObjectNode();
            modelObjectNode.put("name", name);
            modelObjectNode.put("revision", 1);
            description = StringUtils.defaultString(description);
            modelObjectNode.put("description", description);
            modelData.setMetaInfo(modelObjectNode.toString());
            modelData.setName(name);
            modelData.setKey(StringUtils.defaultString(key));
            this.repositoryService.saveModel(modelData);
            this.repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));
            return AjaxResponse.success("ok", "/modeler.html?modelId=" + modelData.getId());
        } catch (Exception var11) {
            this.logger.error("创建模型失败：", var11);
            return AjaxResponse.error("创建模型失败：", var11);
        }
    }

    @RequestMapping({"/deploy/{modelId}"})
    public AjaxResponse deploy(@PathVariable("modelId") String modelId, RedirectAttributes redirectAttributes) {
        try {
            Model e = this.repositoryService.getModel(modelId);
            ObjectNode modelNode = (ObjectNode)(new ObjectMapper()).readTree(this.repositoryService.getModelEditorSource(e.getId()));
            byte[] bpmnBytes = (byte[])null;
            BpmnModel model = (new BpmnJsonConverter()).convertToBpmnModel(modelNode);
            bpmnBytes = (new BpmnXMLConverter()).convertToXML(model);
            String processName = e.getName() + ".bpmn20.xml";
            Deployment deployment = this.repositoryService.createDeployment().name(e.getName()).addString(processName, new String(bpmnBytes)).deploy();
            redirectAttributes.addFlashAttribute("message", "部署成功，部署ID=" + deployment.getId());
        } catch (Exception var9) {
            this.logger.error("根据模型部署流程失败：modelId={}", modelId, var9);
        }

        return AjaxResponse.success("ok");
    }

    @RequestMapping({"/export/{modelId}/{type}"})
    public void export(@PathVariable("modelId") String modelId, @PathVariable("type") String type, HttpServletResponse response) {
        try {
            Model e = this.repositoryService.getModel(modelId);
            BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
            byte[] modelEditorSource = this.repositoryService.getModelEditorSource(e.getId());
            JsonNode editorNode = (new ObjectMapper()).readTree(modelEditorSource);
            BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);
            if(bpmnModel.getMainProcess() == null) {
                response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
                response.getOutputStream().println("no main process, can\'t export for type: " + type);
                response.flushBuffer();
                return;
            }

            String filename = "";
            byte[] exportBytes = (byte[])null;
            String mainProcessId = bpmnModel.getMainProcess().getId();
            if(type.equals("bpmn")) {
                BpmnXMLConverter in = new BpmnXMLConverter();
                exportBytes = in.convertToXML(bpmnModel);
                filename = mainProcessId + ".bpmn20.xml";
            } else if(type.equals("json")) {
                exportBytes = modelEditorSource;
                filename = mainProcessId + ".json";
            }

            response.setHeader("content-type", "application/force-download");
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment; filename=" + filename);
            ByteArrayInputStream in1 = new ByteArrayInputStream(exportBytes);
            IOUtils.copy(in1, response.getOutputStream());
            response.flushBuffer();
        } catch (Exception var13) {
            this.logger.error("导出model的xml文件失败：modelId={}, type={}", new Object[]{modelId, type, var13});
        }

    }

    @RequestMapping({"/delete/{modelId}"})
    public AjaxResponse delete(@PathVariable("modelId") String modelId) {
        this.repositoryService.deleteModel(modelId);
        return AjaxResponse.success("ok");
    }
}
